package com.hundun.hddeal.controller;


import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.hundun.hddeal.dao.*;
import com.hundun.hddeal.entity.*;
import com.hundun.hddeal.enums.MatchType;
import com.hundun.hddeal.response.Result;
import com.hundun.hddeal.response.ResultUtil;
import com.hundun.hddeal.service.FeedbackService;
import com.hundun.hddeal.service.NextOrderService;
import com.hundun.hddeal.service.lmpl.AdUserServiceImpl;
import com.hundun.hddeal.service.lmpl.MtUserServiceImpl;
import com.hundun.hddeal.service.lmpl.RecordServiceImpl;
import com.hundun.hddeal.service.lmpl.TaskOrderServiceImpl;
import com.hundun.hddeal.util.*;
import com.hundun.hddeal.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import static org.assertj.core.util.DateUtil.now;

/**
 * 任务大厅
 * @author 谢
 */
@RestController
@RequestMapping("task")
@Slf4j
public class TaskOrderController {

      @Autowired
      TaskOrderServiceImpl taskOrderService;
      @Autowired
      AdUserServiceImpl adUserService;
      @Autowired
      MtUserServiceImpl mtUserService;
      @Autowired
      NextOrderService nextOrderService;
      @Autowired
      GzhMapper gzhMapper;
      @Autowired
      TaskOrderMapper taskOrderMapper;
      @Autowired
      NextOrderMapper nextOrderMapper;
      @Autowired
      RecordServiceImpl recordService;
      @Autowired
      FeedbackService feedbackService;
      @Autowired
      WordLibraryMapper wordLibraryMapper;
      @Autowired
      RecordMapper recordMapper;
      @Autowired
      AdUserMapper adUserMapper;

      /**
       * 广告方添加广告需求
       * @param taskOrderVo
       * @return
       */
      @PostMapping("add")
      public Result addTask(@RequestBody TaskOrderVo taskOrderVo){
          String token=taskOrderVo.getAdUserToken();
          String adUserId = TokenUtilT.getTokenById(token);
          AdUser adUser = adUserService.findAdUserById(adUserId);
          /*if(taskOrderVo.getAdBudget()>adUser.getAdMoney()){
              return ResultUtil.error("余额不足！");
          }*/
          //生成任务单号
          String orderId = OrderIdUtil.OrderNum();
          if(adUser!=null){

              TaskOrder taskOrder=new TaskOrder();
              taskOrder.setType(taskOrderVo.getType());
              taskOrder.setGzhType(taskOrderVo.getGzhType());
              taskOrder.setReadOne(taskOrderVo.getReadOne());
              taskOrder.setReadTwo(taskOrderVo.getReadTwo());
              taskOrder.setFans(taskOrderVo.getFans());
              taskOrder.setAdId(adUser.getAdId());
              taskOrder.setAdMoney(taskOrderVo.getAdMoney());
              taskOrder.setAdPrice(taskOrderVo.getAdPrice());
              taskOrder.setAdType(taskOrderVo.getAdType());
              taskOrder.setImportText(taskOrderVo.getImportText());
              taskOrder.setMtCity(taskOrderVo.getMtCity());
              taskOrder.setMtSex(taskOrderVo.getMtSex());
              taskOrder.setMtType(taskOrderVo.getMtType());
              taskOrder.setPicture1(taskOrderVo.getPicture1());
              taskOrder.setPicture2(taskOrderVo.getPicture2());
              taskOrder.setPicture3(taskOrderVo.getPicture3());
              taskOrder.setRetainTime(taskOrderVo.getRetainTime());
              taskOrder.setSummary(taskOrderVo.getSummary());

              //base64编码
              Base64.Encoder encoder = Base64.getEncoder();
              byte[] textByte = taskOrderVo.getTextBody().getBytes(StandardCharsets.UTF_8);
              String encodedText = encoder.encodeToString(textByte);
              taskOrder.setTextBody(encodedText);

              taskOrder.setTextTitle(taskOrderVo.getTextTitle());
              taskOrder.setTextTitle2(taskOrderVo.getTextTitle2());
              taskOrder.setTextTitle3(taskOrderVo.getTextTitle3());
              taskOrder.setTgEndtime(taskOrderVo.getTgEndtime());
              taskOrder.setTgStarttime(taskOrderVo.getTgStarttime());
              taskOrder.setIsPostpone(taskOrderVo.getIsPostpone());
              taskOrder.setTfPlace(taskOrderVo.getTfPlace());
              taskOrder.setTextUrl(taskOrderVo.getTextUrl());
              taskOrder.setAdBudget(taskOrderVo.getAdBudget());
              taskOrder.setBackMoney(taskOrderVo.getBackMoney());
              taskOrder.setRealityMoney(taskOrderVo.getRealityMoney());
              taskOrder.setOrderId(orderId);
              taskOrder.setAdName(taskOrderVo.getAdName());
              taskOrder.setOutMoney(taskOrderVo.getAdBudget());
              taskOrder.setUserFz(adUser.getFz());
              taskOrder.setUserName(adUser.getUserName());
              taskOrder.setScoreOne(taskOrderVo.getScoreOne());
              taskOrder.setScoreTwo(taskOrderVo.getScoreTwo());
              Map<String,Long> map=new HashMap<>(16);
              try{
                  taskOrderMapper.insertSelective(taskOrder);
                  map.put("id",taskOrder.getId());
              }catch (Exception e){
                  e.printStackTrace();
                  return ResultUtil.error();
              }
              return ResultUtil.success(map);
          }
          return ResultUtil.error("无token");
      }



     /**
      * 媒体方显示广告任务列表(任务大厅)
      * @return
      */
     @PostMapping("getAll")
     public Result getAll(@RequestBody RequestPageBean pageBean){
         String token=pageBean.getMtUserToken();
         String mtUserId = TokenUtilT.getTokenById(token);
         MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
         if(mtUser!=null){
             return taskOrderService.selectAll(pageBean.getPageNum(),pageBean.getPageSize()
             ,pageBean.getAdType(),pageBean.getType(),pageBean.getTfPlace(),pageBean.getTime());
         }
        return ResultUtil.error("无token");
     }


     /**
      * 查询广告用户任务订单列表
      */
    @PostMapping("ad/getAll")
    public Result getadAll(@RequestBody Map<String ,String> map){
        String adUserId = TokenUtilT.getTokenById(map.get("adUserToken"));
        AdUser adUser = adUserService.findAdUserById(adUserId);
        if (adUser != null) {
            String status1=map.get("status");
            if(status1==null){
                status1="9";
            }
            int status=Integer.parseInt(status1);
           return taskOrderService.selectByAdIdAndStatus(adUserId,map.get("adName"),status
           ,Integer.parseInt(map.get("pageNum")),Integer.parseInt(map.get("pageSize")),map.get("type"));
        }
        return ResultUtil.error();
    }


    /**
     *广告方媒体方查询任务订单详情
     * @param map
     * @return
     */
    @PostMapping("ad/getDetailOne")
    public Result getAdGetDetail(@RequestBody Map<String ,String> map){
        String adtoken=map.get("adUserToken");
        String mttoken=map.get("mtUserToken");
        if(adtoken!=null){
            TokenUtilT.getTokenById(adtoken);
        }else {
            TokenUtilT.getTokenById(mttoken);
        }

        TaskOrder taskOrder=taskOrderMapper.getOne(map.get("orderId"),map.get("type"));
        Base64.Decoder decoder = Base64.getDecoder();
        taskOrder.setTextBody(new String(decoder.decode(taskOrder.getTextBody()), StandardCharsets.UTF_8));
        return ResultUtil.success(taskOrder);
        }



    /**
     * 广告方查询发布任务接单情况
     * @param nextOrderVo
     * @return
     */
    @PostMapping("ad/getDetailTask")
    public Result getNextOrder(@RequestBody NextOrderVo nextOrderVo){
        String token=nextOrderVo.getAdUserToken();
        String adUserId = TokenUtilT.getTokenById(token);
        AdUser adUser = adUserService.findAdUserById(adUserId);
        if(adUser!=null){
            return nextOrderService.selectGetofTask(adUserId,nextOrderVo.getOrderId(),nextOrderVo.getPageNum(),
                    nextOrderVo.getPageSize(),nextOrderVo.getType(),nextOrderVo.getStatus(),nextOrderVo.getGzhName(),nextOrderVo.getOrder());
        }
        return ResultUtil.error("无token");
    }

    /**
     * 广告||媒体查询接单状态的条数
     * @param nextOrderVo
     * @return
     */
    @PostMapping("getStatusCount")
    public Result getStatusCount(@RequestBody NextOrderVo nextOrderVo){
        String adtoken=nextOrderVo.getAdUserToken();
        String mttoken=nextOrderVo.getMtUserToken();
        String adUserId=null;
        String mtUserId=null;
        if(adtoken!=null){
             adUserId = TokenUtilT.getTokenById(adtoken);
        }else {
             mtUserId= TokenUtilT.getTokenById(mttoken);
        }

        StatusCountVo statusCountVo= nextOrderMapper.selectAllStatus(mtUserId,adUserId,nextOrderVo.getOrderId(),nextOrderVo.getHostId());
        if(statusCountVo==null){
            StatusCountVo statusCountVo1=new StatusCountVo();
            statusCountVo1.setZero(0);
            statusCountVo1.setOne(0);
            statusCountVo1.setTwo(0);
            statusCountVo1.setThree(0);
            statusCountVo1.setFour(0);
            statusCountVo1.setFive(0);
            return ResultUtil.success(statusCountVo1);
        }
      return ResultUtil.success(statusCountVo);
    }



    /**
     * 查询媒体用户任务订单列表（已领任务 ->包括万粉阅读）
     * @param nextOrderVo
     * @return
     */
     @PostMapping("mt/getTask")
     public Result getmtTask(@RequestBody NextOrderVo nextOrderVo){
         String token=nextOrderVo.getMtUserToken();
         String mtUserId = TokenUtilT.getTokenById(token);
         MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
         if(mtUser!=null){
             return nextOrderService.selectMtofTask(mtUserId,nextOrderVo.getStatus(),nextOrderVo.getGzhName(),
                     nextOrderVo.getStartTime(),nextOrderVo.getEndTime(),nextOrderVo.getPageNum(),
                     nextOrderVo.getPageSize(),nextOrderVo.getType(),nextOrderVo.getHostId(),nextOrderVo.getOrder());
         }
         return ResultUtil.error("无token");

     }



    /**
     * 媒体任务大厅添加订单
     */
    @PostMapping("addOrder")
    public Result addOrder(@RequestBody NextOrderVo nextOrderVo){
        //获取当前时间
        Date curDate = new Date(System.currentTimeMillis());
        String mtUserId = TokenUtilT.getTokenById(nextOrderVo.getMtUserToken());
        MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
        if(mtUser!=null){
            TaskOrder taskOrder= taskOrderMapper.getOne(nextOrderVo.getOrder(),nextOrderVo.getType());

            if(!(taskOrder.getTgStarttime().getTime()<=nextOrderVo.getTgTime().getTime() &&
                    nextOrderVo.getTgTime().getTime()<=taskOrder.getTgEndtime().getTime())){
                  return ResultUtil.error("推广时间不在范围内！");
            }
            String[] ghIds= nextOrderVo.getGhIds();
            if("万粉".equals(nextOrderVo.getType())){
                List<Gzh> gzhs=gzhMapper.selectByGhIds(ghIds);
                double money=0.00;
                for(Gzh gzh:gzhs){
                    money+=gzh.getGzhFans()/(double)10000;
                    gzh.setOrderTime(now());
                    gzh.setScoreReceipt(0);
                    //接单扣分
                    gzhMapper.updateByPrimaryKeySelective(gzh);
                }
                if(taskOrder.getOutMoney()-money<0){
                    return ResultUtil.error("超过预算金额");
                }
            }else {
                double surolus=taskOrder.getAdBudget()-(double)Math.round(taskOrder.getAdBudget()/1.1);
                if(nextOrderVo.getYjMoney()>taskOrder.getOutMoney()-surolus){
                    return ResultUtil.error("广告金额不足下单！");
                }
            }

            //生成主id
            String hostId = OrderIdUtil.OrderNum();
            ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("thread-call-runner-%d").build();
            int size = ghIds.length;
            ExecutorService fixedThreadPool = new ThreadPoolExecutor(size,size,0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024),namedThreadFactory);
            try{
                for(int i=0;i<size;i++){
                    final int index = i;
                    fixedThreadPool.execute(() -> {
                        TaskOrder taskOrder1 = taskOrderMapper.getOne(nextOrderVo.getOrder(),nextOrderVo.getType());
                        double hour;
                        if(taskOrder1.getRetainTime()==24){
                            hour=1.3;
                        }else if(taskOrder1.getRetainTime()==48){
                            hour=3;
                        }else {
                            hour=4;
                        }
                        GzhBody gzh = gzhMapper.selectByPrimaryKey(ghIds[index]);
                        NextOrder nextOrder=new NextOrder();
                        nextOrder.setType(nextOrderVo.getType());
                        if("万粉".equals(nextOrderVo.getType())){
                            nextOrder.setStatus((byte)0);
                            Double yuji=(double)gzh.getGzhFans()/10000;
                            nextOrder.setYjMoney(yuji* taskOrder1.getAdPrice());
                        }else {
                            //计算预计收入
                            if("多图文头条".equals(taskOrder1.getTfPlace())){
                            nextOrder.setYjMoney(gzh.getReadnumAv()* taskOrder1.getAdPrice()*hour);
                            }else if("多图文次条".equals(taskOrder1.getTfPlace())){
                            nextOrder.setYjMoney(gzh.getNreadnumAv()* taskOrder1.getAdPrice());
                            }else {
                            nextOrder.setYjMoney(gzh.getThreenumAv()* taskOrder1.getAdPrice());
                            }

                        }
                        nextOrder.setHostId(hostId);
                        nextOrder.setAdName(taskOrder1.getAdName());
                        nextOrder.setAdId(taskOrder1.getAdId());
                        nextOrder.setAdPrice(taskOrder1.getAdPrice());
                        nextOrder.setGhId(ghIds[index]);
                        nextOrder.setMtId(mtUser.getMtId());
                        nextOrder.setOrder(OrderIdUtil.OrderNum());
                        nextOrder.setOrderId(nextOrderVo.getOrder());
                        nextOrder.setTgTime(nextOrderVo.getTgTime());
                        nextOrder.setGzhName(gzh.getGzhName());
                        nextOrder.setTextTitle(nextOrderVo.getTextTitle());
                        nextOrder.setTgPlace(taskOrder1.getTfPlace());
                        nextOrder.setUserFz(taskOrder1.getUserFz());
                        nextOrder.setUserName(taskOrder1.getUserName());
                        nextOrder.setCreateDate(curDate);
                        nextOrder.setDitchFz(mtUser.getFz());
                        nextOrder.setDitchName(mtUser.getUserName());
                        nextOrderService.insertSelective(nextOrder);
                        //扣除金额
                        if("万粉".equals(nextOrderVo.getType())){
                            taskOrderService.updateOutMoney(nextOrderVo.getOrder(),((double)gzh.getGzhFans()/10000)* taskOrder1.getAdPrice());
                        }else {
                            if("多图文头条".equals(taskOrder1.getTfPlace())){
                                taskOrderService.updateOutMoney(nextOrderVo.getOrder(),gzh.getReadnumAv()* taskOrder1.getAdPrice()*hour);
                            }else if("多图文次条".equals(taskOrder1.getTfPlace())){
                                taskOrderService.updateOutMoney(nextOrderVo.getOrder(),gzh.getNreadnumAv()* taskOrder1.getAdPrice());
                            }else {
                                taskOrderService.updateOutMoney(nextOrderVo.getOrder(),gzh.getThreenumAv()* taskOrder1.getAdPrice());
                            }

                        }

                    });

                }
                //如果金额为零则状态改为执行中
                if(nextOrderVo.getYjMoney()-taskOrder.getOutMoney()==0){
                    taskOrderService.updateStatus(nextOrderVo.getOrder(),2);
                }
                fixedThreadPool.shutdown();
                return ResultUtil.success();
            }catch (Exception e){
                e.printStackTrace();
                return ResultUtil.error();
            }
        }
        return ResultUtil.error("无token");
    }

    /**
     * 广告方查看金额是否足够
     * @param adUserVo
     * @return
     */
    @PostMapping("adPayment")
    public Result payment(@RequestBody AdUserVo adUserVo){
        String token = adUserVo.getAdUserToken();
        String adUserId = TokenUtilT.getTokenById(token);
        AdUser adUser = adUserService.findAdUserById(adUserId);
        if(adUser!=null){
            /*if(adUser.getAdMoney()<adUserVo.getMoney()){
                return ResultUtil.error("金额不足！");
            }*/
            return ResultUtil.success();
        }
        return ResultUtil.error("无token");
    }


    /**
     * 媒体方添加执行链接
     * @param nextOrderVo
     * @return
     */
    @PostMapping("setPostUrl")
    public Result setPostUrl(@RequestBody NextOrderVo nextOrderVo){
        String mtUserId = TokenUtilT.getTokenById(nextOrderVo.getMtUserToken());
        MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
        NextOrder next=nextOrderMapper.selectByPrimaryKey(nextOrderVo.getId());
        if(next.getPostUrl()!=null){
            return ResultUtil.error("请不要重复添加执行链接！");
        }

            if(mtUser!=null){
            NextOrder nextOrder=new NextOrder();
            nextOrder.setPostUrl(nextOrderVo.getPostUrl());
            nextOrder.setId(nextOrderVo.getId());
            nextOrder.setStatus((byte)2);
            nextOrder.setRealityTime(now());
            return nextOrderService.updateByPrimaryKeySelective(nextOrder);
        }
        return ResultUtil.error();
    }


    /**
     * 广告方追加费用
     */
   @PostMapping("addToMoney")
   public Result addToMoney(@RequestBody AdUserVo adUserVo){
       String token = adUserVo.getAdUserToken();
       String adUserId = TokenUtilT.getTokenById(token);
       AdUser adUser = adUserService.findAdUserById(adUserId);
       if(adUser!=null){

           TaskOrder taskOrder=taskOrderMapper.getOne(adUserVo.getOrderId(),adUserVo.getType());
           //如果是未审核未付款不扣取费用
           if(taskOrder.getStatus()==0){
               taskOrder.setAdBudget(taskOrder.getAdBudget()+adUserVo.getMoney());
               taskOrder.setOutMoney(taskOrder.getOutMoney()+adUserVo.getMoney());
               return taskOrderService.updateByPrimaryKeySelective(taskOrder);
           }

           //判断支付密码是否正确
           if(!MD5Util.getSaltverifyMD5(adUserVo.getPayPwd(),adUser.getPayPwd())){
               return ResultUtil.error("支付密码不正确");
           }

           if(adUser.getAdMoney()-adUserVo.getMoney()<0){
               return ResultUtil.error("账号余额不足！");
           }
           adUserService.updateMoney(adUserId,adUserVo.getMoney());
           adUserService.updateIceMoney(adUserId,adUserVo.getMoney());

           if(taskOrder.getStatus()!=0){
               taskOrder.setStatus((byte)1);
           }
           Record record =new Record();
           record.setUserId(adUserId);
           record.setMoney(adUserVo.getMoney());
           record.setOrderId(adUserVo.getOrderId());
           record.setYyName(taskOrder.getAdName());
           record.setStatus((byte)1);
           record.setContent("冻结记录");
           record.setUserFz(adUser.getFz());
           record.setUserName(adUser.getUserName());
           recordService.insertSelective(record);

           Record record1 =new Record();
           record1.setUserId(taskOrder.getAdId());
           record1.setMoney(adUserVo.getMoney());
           record1.setOrderId(adUserVo.getOrderId());
           record1.setYyName(taskOrder.getAdName());
           record1.setStatus((byte)4);
           record1.setGzhName("追加费用");
           record1.setContent("消费记录");
           record1.setUserFz(adUser.getFz());
           record1.setUserName(adUser.getUserName());
           recordService.insertSelective(record1);


           taskOrder.setAdBudget(taskOrder.getAdBudget()+adUserVo.getMoney());
           taskOrder.setOutMoney(taskOrder.getOutMoney()+adUserVo.getMoney());
           return taskOrderService.updateByPrimaryKeySelective(taskOrder);

       }
         return ResultUtil.error("无token");
   }


    /**
     * 媒体方查看任务订单详情
     */
   @PostMapping("getOrderMt")
   public Result getOrderMt(@RequestBody TaskOrderVo taskOrderVo){
       String mtUserId = TokenUtilT.getTokenById(taskOrderVo.getMtUserToken());
       MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
       if(mtUser!=null){
          return taskOrderService.getOne(taskOrderVo.getOrderId(),mtUserId,taskOrderVo.getGhId(),taskOrderVo.getId(),taskOrderVo.getType());
       }
       return ResultUtil.error("无token");
   }


    /**
     * 万粉任务 || 阅读任务 ->订单付款
     * @param taskOrderVo
     * @return
     */
   @PostMapping("payTask")
   public Result payTask(@RequestBody TaskOrderVo taskOrderVo){
       String token=taskOrderVo.getAdUserToken();
       String adUserId = TokenUtilT.getTokenById(token);
       AdUser adUser = adUserService.findAdUserById(adUserId);
       //判断支付密码是否正确
       if(!MD5Util.getSaltverifyMD5(taskOrderVo.getPayPwd(),adUser.getPayPwd())){
           return ResultUtil.error("支付密码不正确");
       }

       TaskOrder taskOrder=taskOrderMapper.getOne(taskOrderVo.getOrderId(),taskOrderVo.getType());
       log.info(adUserId+"进来任务订单付款:现有金额:"+adUser.getAdMoney()+",订单金额:"+taskOrder.getAdBudget());
       if(adUser.getAdMoney()<taskOrder.getAdBudget()){
           log.info("进来余额不足");
           return ResultUtil.error("账户余额不足！");
       }
       Record record =new Record();
       record.setUserId(taskOrder.getAdId());
       record.setMoney(taskOrder.getAdBudget());
       record.setOrderId(taskOrderVo.getOrderId());
       record.setYyName(taskOrder.getAdName());
       record.setContent("冻结记录");
       record.setGzhName("");
       record.setStatus((byte) 1);
       record.setUserFz(adUser.getFz());
       record.setUserName(adUser.getUserName());
       recordService.insertSelective(record);

       Record record1 =new Record();
       record1.setUserId(taskOrder.getAdId());
       record1.setMoney(taskOrder.getAdBudget());
       record1.setOrderId(taskOrderVo.getOrderId());
       record1.setYyName(taskOrder.getAdName());
       record1.setStatus((byte)4);
       record1.setGzhName("");
       record1.setContent("消费记录");
       record1.setUserFz(adUser.getFz());
       record1.setUserName(adUser.getUserName());
       recordService.insertSelective(record1);
       //添加冻结金额
       adUserService.updateIceMoney(adUserId,taskOrder.getAdBudget());
       adUserService.updateMoney(adUserId,taskOrder.getAdBudget());
       taskOrder.setStatus((byte)1);
       taskOrderService.updateByPrimaryKeySelective(taskOrder);
       log.info(adUserId+"完成付款");
       return ResultUtil.success();
   }


    /**
     * 媒体广告改变订单状态
     * @param nextOrderVo
     * @return
     */
   @PostMapping("setStatus")
   public Result setStatus(@RequestBody NextOrderVo nextOrderVo){
       String mttoken= nextOrderVo.getMtUserToken();
       String adtoken=nextOrderVo.getAdUserToken();
       NextOrder nextOrder1=new NextOrder();
       nextOrder1.setStatus(nextOrderVo.getStatus());
       nextOrder1.setIds(nextOrderVo.getIds());
       List<NextOrder> nextOrders= nextOrderMapper.idsOrder(nextOrderVo.getIds());
       if(mttoken!=null){
           String mtUserId = TokenUtilT.getTokenById(mttoken);
           MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
           if(mtUser==null){
               return ResultUtil.error("无token!");
           }
           for(NextOrder nextOrder:nextOrders) {
               if (!(nextOrderVo.getStatus() == 2 && nextOrder.getStatus() == 1)) {
                   return ResultUtil.error("当前有订单状态不可修改!");
               }
           }
         return nextOrderService.updateByPrimaryKeySelective(nextOrder1);


       }else if(adtoken!=null){
           String adUserId = TokenUtilT.getTokenById(adtoken);
           AdUser adUser = adUserService.findAdUserById(adUserId);
           if(adUser==null){
               return ResultUtil.error("无token!");
           }

               for(NextOrder nextOrder:nextOrders){
                   if(nextOrderVo.getStatus()==2 && nextOrder.getStatus()==4){
                   Feedback feedback=new Feedback();
                   feedback.setOrder(nextOrder.getOrder());
                   feedback.setMessage(nextOrderVo.getMessage());
                   feedbackService.insertSelective(feedback);
               }else if(!(nextOrderVo.getStatus()==5 && nextOrder.getStatus()==4)){
                   return ResultUtil.error("当前有订单状态不可修改!");
                   }
           }
           return nextOrderService.updateByPrimaryKeySelective(nextOrder1);
       }
        return ResultUtil.error();
   }


    /**
     * 媒体查询已领任务主id集合(包括万粉和阅读)
     * @param nextOrderVo
     * @return
     */
   @PostMapping("getMtHostList")
   public Result getMtHostList(@RequestBody NextOrderVo nextOrderVo){
       String mttoken= nextOrderVo.getMtUserToken();
       String mtUserId = TokenUtilT.getTokenById(mttoken);
       MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
       if(mtUser!=null){
           return nextOrderService.mtHostList(mtUserId,nextOrderVo.getHostId(),
                   nextOrderVo.getStartTime(),nextOrderVo.getEndTime(),nextOrderVo.getPageNum(),
                   nextOrderVo.getPageSize(),nextOrderVo.getType());
       }
       return ResultUtil.error();


   }


    /**
     * 导出要上传预览链接的表
     * @param token
     * @param hostId
     * @param response
     * @return
     */
   @GetMapping("exportOrderLookUrl")
   public void exportOrderLookUrl(@RequestParam("mtUserToken") String token, @RequestParam("hostId") String hostId,HttpServletResponse response) throws IOException {
       String mtUserId = TokenUtilT.getTokenById(token);
       List<NextOrder> nextOrders=nextOrderMapper.selectMtofTask(mtUserId,(byte)2,null,
               null,null, "万粉",hostId,null);
       EasyPoiUtil.exportExcel(nextOrders,null,"sheet1",NextOrder.class,"预览链接数据表.xls",true,response);
   }

    /**
     * 导出要上传执行链接的表
     * @param token
     * @param hostId
     * @param response
     * @return
     */
   @GetMapping("exportOrderTakeUrl")
   public void exportOrderTakeUrl(@RequestParam("mtUserToken") String token, @RequestParam("hostId") String hostId,HttpServletResponse response) throws IOException {
       String mtUserId = TokenUtilT.getTokenById(token);
       List<NextOrder> nextOrders=nextOrderMapper.selectMtofTask(mtUserId,(byte)5,null,
               null,null, "万粉",hostId,null);
       EasyPoiUtil.exportExcel(nextOrders,null,"sheet1",NextOrder.class,"执行链接数据表.xls",true,response);
   }


    /**
     * 媒体方导入要批量上传的执行链接订单表
     * @param
     * @return
     */
    @PostMapping("importOrderPostUrl")
    public Result importOrderTakeUrl(@RequestParam("mtUserToken")String token,@RequestParam("file") MultipartFile file){
        String mtUserId = TokenUtilT.getTokenById(token);
        MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
        if(mtUser!=null) {
            List<NextOrder> nextOrders = EasyPoiUtil.importExcel(file,0,1,NextOrder.class);
            StringBuilder buf = new StringBuilder();
            for (NextOrder nextOrder : nextOrders) {
                if(nextOrder.getPostUrl()!=null){
                    nextOrder.setStatus((byte) 6);
                    nextOrder.setUpdateDate(now());
                    nextOrder.setRealityTime(now());
                    nextOrder.setLookUrl(null);
                    nextOrderMapper.updateSomeUrl(nextOrder);
                }else {
                    buf.append(nextOrder.getGzhName()).append(",");
                }
            }
            if (buf.length()!=0) {
                return ResultUtil.error(buf.toString()+"该订单上传执行链接有误，请核实后再上传!");
            }
            return ResultUtil.success();
        }
        return ResultUtil.error();
    }



    /**
     * 媒体方导入要批量上传的预览链接订单表
     * @param
     * @return
     */
    @PostMapping("importOrderLookUrl")
    public Result importOrderLookUrl(@RequestParam("mtUserToken")String token,@RequestParam("file") MultipartFile file){
        String mtUserId = TokenUtilT.getTokenById(token);
        MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
        if(mtUser!=null){
            List<NextOrder> nextOrders = EasyPoiUtil.importExcel(file,0,1,NextOrder.class);
            StringBuilder buf = new StringBuilder();
            for(NextOrder nextOrder:nextOrders){
                if(nextOrder.getLookUrl()!=null){
                    nextOrder.setStatus((byte)4);
                    nextOrder.setTakeUrl(null);
                    nextOrder.setPostUrl(null);
                    nextOrderMapper.updateSomeUrl(nextOrder);
                }else {
                    buf.append(nextOrder.getGzhName()).append(",");
                }
            }
            if (buf.length()!=0) {
                return ResultUtil.error(buf.toString()+"该订单上传预览链接有误，请核实后再上传!");
            }
            return ResultUtil.success();
        }
        return ResultUtil.error();
    }


    /**
     * 万粉单个上传预览或执行链接
     * @param nextOrderVo
     * @return
     */
    @PostMapping("setOneUrl")
    public Result oneSetUrl(@RequestBody NextOrderVo nextOrderVo){
        String mtUserId = TokenUtilT.getTokenById(nextOrderVo.getMtUserToken());
        MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
        if(mtUser!=null){
            NextOrder nextOrder=new NextOrder();
            nextOrder.setOrder(nextOrderVo.getOrder());
            nextOrder.setLookUrl(nextOrderVo.getLookUrl());
            nextOrder.setPostUrl(nextOrderVo.getPostUrl());
            nextOrder.setStatus(nextOrderVo.getStatus());
            nextOrder.setUpdateDate(now());
            if(nextOrderVo.getPostUrl()!=null){
                nextOrder.setRealityTime(now());
            }
            nextOrderMapper.updateSomeUrl(nextOrder);
            return ResultUtil.success();
        }
        return ResultUtil.error("无token");
    }


    /**
     * 阅读查看各个条数
     */
    @PostMapping("getReadStatus")
    public Result getReadStatus(@RequestBody NextOrderVo nextOrderVo){
        String mtUserId = TokenUtilT.getTokenById(nextOrderVo.getMtUserToken());
        MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
        if(mtUser!=null){
            StatusCountVo statusCountVo= nextOrderMapper.selectReadStatus(mtUserId,nextOrderVo.getHostId(),nextOrderVo.getType());
            if(statusCountVo==null){
                StatusCountVo statusCount=new StatusCountVo();
                return ResultUtil.success(statusCount);
            }
            return ResultUtil.success(statusCountVo);
        }
        return ResultUtil.error("无token");
    }



    /**
     * 导出要上传执行链接的表（阅读）
     * @param token
     * @param hostId
     * @param response
     * @return
     */
    @GetMapping("exportReadUrl")
    public void exportOrderPostUrl(@RequestParam("mtUserToken") String token, @RequestParam("hostId") String hostId,HttpServletResponse response) throws IOException {
        String mtUserId = TokenUtilT.getTokenById(token);
        List<NextOrder> nextOrders=nextOrderMapper.selectMtofTask(mtUserId,(byte)1,null,
                null,null, "阅读",hostId,null);
        EasyPoiUtil.exportExcel(nextOrders,null,"sheet1",NextOrder.class,"执行链接数据表.xls",true,response);
    }


    /**
     * 导入要批量上传的执行链接订单表（阅读）
     * @param
     * @return
     */
    @PostMapping("importReadPostUrl")
    public Result importOrderPostUrl(@RequestParam("mtUserToken")String token,@RequestParam("file") MultipartFile file){
        String mtUserId = TokenUtilT.getTokenById(token);
        MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
        if(mtUser!=null) {
            List<NextOrder> nextOrders = EasyPoiUtil.importExcel(file,0,1,NextOrder.class);
            StringBuilder buf = new StringBuilder();
            for (NextOrder nextOrder : nextOrders) {
                if(nextOrder.getPostUrl()!=null){
                    nextOrder.setStatus((byte)2);
                    nextOrder.setUpdateDate(now());
                    nextOrder.setRealityTime(now());
                    nextOrderMapper.updateSomeUrl(nextOrder);
                }else {
                    buf.append(nextOrder.getGzhName()).append(",");
                }
            }
            if (buf.length()!=0) {
                return ResultUtil.error(buf.toString()+"该订单上传执行链接有误，请核实后再上传!");
            }
            return ResultUtil.success();
        }
        return ResultUtil.error();
    }

    /**
     * 检查标题是否有敏感词
     * @param taskOrderVo
     * @return
     */
    @PostMapping("checkTitle")
    public Result checkTitle(@RequestBody TaskOrderVo taskOrderVo){
        String text=taskOrderVo.getTextTitle();
        //查敏感库
        Set<String> sensitiveWords=wordLibraryMapper.selectAll();
        TextFilterUtil textFilter=new TextFilterUtil();
        textFilter.initSensitiveWordsMap(sensitiveWords);
        //配对
        Set<String> sensitiveWords1=textFilter.getSensitiveWords(text, MatchType.MAX_MATCH);
        if(sensitiveWords1.size()==0){
            return ResultUtil.success();
        }
        return ResultUtil.error("该标题含有敏感词:"+sensitiveWords1);
    }


    /**
     * 广告方导出预约了的公众号
     * @param
     * @return
     */
    @GetMapping("exportTaskGzh")
    public void exportOrderGzh(@RequestParam("adUserToken") String token, @RequestParam("order") String order,@Param("type")String type,
                               HttpServletResponse response) throws IOException {
        String adUserId = TokenUtilT.getTokenById(token);
        List<NextOrderPuls> nextOrderPulsList = nextOrderMapper.selectGetofTask(adUserId,order,type,null,null,null);
        EasyPoiUtil.exportExcel(nextOrderPulsList,null,"sheet1",NextOrderPuls.class,"订单公众号.xls",true,response);
    }

    /**
     * 媒体方导出预约了的公众号
     * @param token
     * @param hostId
     * @param type
     * @param response
     * @throws IOException
     */
    @GetMapping("exportMtOrderGzh")
    public void exportMtOrderGzh(@RequestParam("mtUserToken") String token, @RequestParam("hostId") String hostId,@Param("type")String type,
                                 HttpServletResponse response)throws IOException{
        String mtUserId = TokenUtilT.getTokenById(token);
        List<NextOrder> nextOrderList = nextOrderMapper.selectMtofTask(mtUserId,null,null,null,null,type,hostId,null);
        TaskOrder taskOrder = taskOrderMapper.getOne(nextOrderList.get(0).getOrderId(),type);
        for (NextOrder nextOrder:nextOrderList) {
            nextOrder.setAdPrice(taskOrder.getAdPrice());
            if("万粉".equals(nextOrder.getType())){
                nextOrder.setTakeUrl(nextOrder.getTakeUrl());
            }else {
                nextOrder.setTakeUrl(nextOrder.getPostUrl());
            }
        }
        EasyPoiUtil.exportExcel(nextOrderList,null,"sheet1",NextOrder.class,"订单公众号.xls",true,response);
    }


    /**
     * 广告被后台拒绝再次编辑
     * @param taskOrder
     * @return
     */
    @PostMapping("updateTextBody")
    public Result updateTextBody(@RequestBody TaskOrder taskOrder){
        if(taskOrder.getAdPrice()!=null&&taskOrder.getAdPrice()<0.2){
            return ResultUtil.error("价格不能低于0.2");
        }
        TaskOrder taskOrder1=taskOrderMapper.selectByPrimaryKey(taskOrder.getId());
        if(taskOrder1.getStatus()==0 ||taskOrder1.getStatus()==13||taskOrder1.getStatus()==7){
            //未审核未付款修改文案变未审核
            if(taskOrder.getAdPrice()==null&&taskOrder.getTextBody()!=null){
                taskOrder.setStatus((byte)0);
            }
        }else {
            if(taskOrder.getAdPrice()==null&&taskOrder.getTextBody()!=null){
                taskOrder.setStatus((byte)14);
            }
            if(taskOrder.getTgEndtime()!=null){
                taskOrder.setTgEndtime(taskOrder.getTgEndtime());
            }
        }

        //base64编码
        if(taskOrder.getTextBody()!=null){
            Base64.Encoder encoder = Base64.getEncoder();
            byte[] textByte = taskOrder.getTextBody().getBytes(StandardCharsets.UTF_8);
            String encodedText = encoder.encodeToString(textByte);
            taskOrder.setTextBody(encodedText);
        }
        return taskOrderService.updateByPrimaryKeySelective(taskOrder);
    }

    /**
     * 取消订单(订单没人接则取消，有付款则退款)
     * @param taskOrderVo
     * @return
     */
    @PostMapping("cancelOrder")
    public Result cancelOrder(@RequestBody TaskOrderVo taskOrderVo){
        TaskOrder taskOrder= taskOrderMapper.selectByPrimaryKey(taskOrderVo.getId());
        List<NextOrder> nextOrders=nextOrderMapper.getAll(taskOrder.getOrderId());
        if(nextOrders.size()!=0){
            return ResultUtil.error("该订单已有媒体接单,不得取消!");
        }
        if(taskOrder.getStatus()!=13 && taskOrder.getStatus()!=6 &&taskOrder.getStatus()!=0&&taskOrder.getStatus()!=7){
            AdUser adUser = adUserService.findAdUserById(taskOrder.getAdId());
            Record record = new Record();
            record.setUserId(taskOrder.getAdId());
            record.setOrderId(taskOrder.getOrderId());
            record.setStatus((byte) 2);
            record.setMoney(taskOrder.getAdBudget());
            record.setYyName("任务订单取消退款");
            record.setUpdateDate(now());
            record.setContent("退款记录");
            record.setUserFz(adUser.getFz());
            recordMapper.insertSelective(record);
            //减去冻结金额
            adUserMapper.updateIceMoney(taskOrder.getAdId(), -taskOrder.getAdBudget());
            //增加用户金额
            adUserMapper.updateMoney(taskOrder.getAdId(), -taskOrder.getAdBudget());
        }
        taskOrder.setStatus((byte)6);
        taskOrderService.updateByPrimaryKeySelective(taskOrder);
        return ResultUtil.success();
    }




}
